package com.srini.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.srini.pojos.LoggedInUser;
import com.srini.util.AppUtil;
import com.srini.util.ConnectionUtil;
import com.srini.util.Constants;
import com.vssr.persist.DataBaseWriter;
import com.vssr.persist.DomainObject;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		LoggedInUser user = (LoggedInUser) request.getSession().getAttribute(
				Constants.LOGGEDIN_USER);
		String fwdPage = "";
		if (user != null) {
			fwdPage = "/home.jsp";
		} else {
			String userName = request.getParameter("username");
			String password = request.getParameter("password");
			Connection conn = new ConnectionUtil().getConnection();
			userName = userName == null ? "" : userName.toUpperCase();
			String query = "select * from USERTABLE where upper(username) = '"
					+ userName + "'";
			List userList = null;
			try {
				userList = DomainObject.getDBRecords(new LoggedInUser(), query,
						conn);
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (userList != null && !userList.isEmpty()) {
				user = (LoggedInUser) userList.get(0);
				if (user.getPassword().equals(password)) {
					request.getSession().setAttribute(Constants.LOGGEDIN_USER,
							user);
					if (AppUtil.isEmpty(user.getLastLogin())) {
						request.setAttribute("firstLogin", true);
						request.setAttribute("message",
								"Please fill in your details.");
						request.setAttribute("currentPage", "userprofile");
					}
					fwdPage = "/home.jsp";
					user.setLastLogin(Calendar.getInstance().getTime()
							.toString());
					DataBaseWriter.update(user);
				} else {
					request.setAttribute("message", "Error::Invalid Password");
					fwdPage = "/login.jsp";
				}
			} else {
				if (!AppUtil.isEmpty(userName)) {
					System.out.println("No user exists with " + userName);
					request.setAttribute("message", "Error::No user Exists");
				}
				fwdPage = "/login.jsp";
			}
		}
		request.getRequestDispatcher(fwdPage).forward(request, response);
	}
}
